package com.example.myapplication.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.myapplication.MainActivity;
import com.example.myapplication.R;
import com.example.myapplication.apiService.api;
import com.example.myapplication.bean.ArticleBeen;
import com.example.myapplication.bean.AttractionsBean;
import com.example.myapplication.utils.RetrofitUtils;
import com.example.myapplication.widget.MultipleStatusView;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ArticleActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    MultipleStatusView article_mv;
    RecyclerView attraction_rv;
    SwipeRefreshLayout swipeRefreshLayout;
    String pageToken = "1";
    int token = 1;
    boolean hasNext;

    BaseQuickAdapter<ArticleBeen.DataBean, BaseViewHolder> adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        initView();
        initData();
    }

    private void initView() {
        article_mv = findViewById(R.id.article_mv);
        attraction_rv = findViewById(R.id.article_rv);
        swipeRefreshLayout = findViewById(R.id.content_view);
        swipeRefreshLayout.setOnRefreshListener(this);
        attraction_rv.setLayoutManager(new LinearLayoutManager(this));
        article_mv.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                article_mv.showLoading();
                initData();
            }
        });
        article_mv.showLoading();
    }

    @SuppressLint("CheckResult")
    private void initData() {
        RetrofitUtils.getInstance().getApiServier(api.class)
                .getArticle(MainActivity.CityCode, "2", pageToken, MainActivity.KEY)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ArticleBeen>() {
                    @Override
                    public void accept(ArticleBeen articleBeen) throws Exception {
                        Log.e("!!!!!!",articleBeen.getRetcode()+"");
                        if (articleBeen.getRetcode().equals("000000")) {
                            article_mv.showContent();
                            hasNext = articleBeen.isHasNext();
                            if (adapter == null) {
                                initAdapter(articleBeen.getData());
                            } else {
                                if (swipeRefreshLayout.isRefreshing()) {
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                                adapter.setNewData(articleBeen.getData());
                                adapter.notifyDataSetChanged();
                            }
                        } else {
                            article_mv.showError();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        article_mv.showError();
                        Log.e("!!!!!!!",throwable.getMessage()+"");
                    }
                });
    }

    @SuppressLint("CheckResult")
    private void loadMoreDatas() {

        RetrofitUtils.getInstance().getApiServier(api.class)
                .getArticle(MainActivity.CityCode, "2", String.valueOf(token), MainActivity.KEY)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ArticleBeen>() {
                    @Override
                    public void accept(ArticleBeen articleBeen) throws Exception {
                        if (articleBeen.getRetcode().equals("000000")) {
                            hasNext = articleBeen.isHasNext();
                            if (adapter != null) {
                                adapter.addData(articleBeen.getData());
                                adapter.notifyDataSetChanged();
                                adapter.loadMoreComplete();
                            }
                        } else {
                            adapter.loadMoreFail();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        adapter.loadMoreFail();
                    }
                });
    }

    private void initAdapter(List<ArticleBeen.DataBean> list) {
        adapter = new BaseQuickAdapter<ArticleBeen.DataBean, BaseViewHolder>(R.layout.item_attraction, list) {
            @Override
            protected void convert(BaseViewHolder helper, ArticleBeen.DataBean item) {
                Glide.with(mContext).load(item.getAvatarUrl()).into((ImageView) helper.getView(R.id.news_img));
                helper.setText(R.id.news_title_tv, item.getTitle()).setText(R.id.news_content_tv, item.getContent()).setText(R.id.news_source_tv, item.getPosterScreenName());
            }
        };
        adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        adapter.isFirstOnly(true);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArticleBeen.DataBean dataBean = (ArticleBeen.DataBean) adapter.getData().get(position);
                Intent intent = new Intent(ArticleActivity.this, DetailsActivity.class);
                intent.putExtra("url", dataBean.getUrl());
                startActivity(intent);
            }
        });
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (hasNext) {
                    token++;
                    loadMoreDatas();
                } else {
                    adapter.loadMoreEnd();
                }
            }
        }, attraction_rv);
        attraction_rv.setAdapter(adapter);
    }


    @Override
    public void onRefresh() {
        initData();
    }
}
